<?php

namespace Common\Model;
use Think\Model;

class UserCarModel extends Model {

	Const STATUS_INIT = 0;		//初始化状态
	Const STATUS_PASS = 1;		//通过审核，可以登录
  Const STATUS_NOT_PASS = 2;    //不通过审核，不可以登录

	protected $tableName = 'user_car';

	protected $_validate = array(
		['phone','/^1[34578]\d{9}$/','手机号不正确'],
    ['phone','','手机号不能重复',self::MUST_VALIDATE ,'unique'],
    ['plate_number','','车牌号不能重复',self::MUST_VALIDATE ,'unique'],
    ['password','require','需要填写密码',self::MUST_VALIDATE],
    ['password','/\w{6,18}/','密码应为6-18位数字字母或_',self::MUST_VALIDATE],
   );

 	protected $_auto = array (
 		['create_time','time',self::MODEL_INSERT,'function'],
 		['password','getPassword',self::MODEL_INSERT,'callback'],
 		['status',self::STATUS_INIT]
  );

 	/**
 	 * 生成密码
 	 */
 	public function getPassword($password){
 		return md5(C('PASSWORD_SALT').$password);
 	}

  /**
   * 判断用户是否存在
   * @return boolean [description]
   */
  public function isPhoneExist($phone){
    return (boolean)$this->where(['phone'=>$phone])->find();
  }

  /**
   * 判断车牌号码是否存在
   * @param  [type]  $plate_number [description]
   * @return boolean               [description]
   */
  public function isPalteNumberExist($plate_number){
    return (boolean)$this->where(['plate_number'=>$plate_number])->find();
  }

  /**
   * 用户是否存在
   * @param  [type]  $phone        [description]
   * @param  [type]  $plate_number [description]
   * @return boolean               [description]
   */
  public function canRegister($phone,$plate_number){
     if($this->isPhoneExist($phone)){
        return '手机号码已存在，不能注册';
     }
     if($this->isPalteNumberExist($plate_number)){
      return '车牌号码已存在，不能注册';
     }
     //可以注册
     return true;
  }

  /**
   * 获取token
   */
  public function getToken(){

    if(!$this->token){
      return $this->makeToken();
    }

    return $this->token;
  }

  /**
   * 生成token并保存
   */
  public function makeToken(){
    $token = md5(uniqid().time());
    $this->token = $token;
    $this->save();
    return $token;
  }

}